package com.leetroll.media.job;

import com.leetroll.api.service.ItemService;
import com.leetroll.common.entity.Item;
import com.leetroll.common.enums.EFileType;
import com.leetroll.media.service.UpDownloadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.Objects;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 电子书资源入库
 */
@Service
@Slf4j
public class Job_Doc {

    private static final String FILE_PATH = "F:\\test\\#doc";

    private final ExecutorService executor = Executors.newFixedThreadPool(10);

    private final ItemService itemService;
    private final UpDownloadService upDownloadService;

    @Autowired
    public Job_Doc(ItemService itemService, UpDownloadService upDownloadService) {
        this.itemService = itemService;
        this.upDownloadService = upDownloadService;
    }

    public void upload() throws InterruptedException {
        File folder = new File(FILE_PATH);
        if (!folder.exists() || !folder.isDirectory()) return;

        File[] docFolders = folder.listFiles();
        if (docFolders == null) return;

        for (File docFolder : docFolders) {
            executor.submit(() -> {
                        try {
                            uploadFile(docFolder);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
            );
        }
        Thread.sleep(1000L * 60 * 60 * 24 * 365);
        log.info("item 插入任务完成");
    }

    private void uploadFile(File docFolder) throws IOException {
        log.info("准备插入 item : {}", docFolder.getName());
        String name = docFolder.getName();
        //插入item表
        Item item = new Item();
        item.setName(name);
        item.setAlias(name);
//        item.setType(EItemType.DOC.getType());
        item.setAuthor("");
        item.setPrice(0.0);
        item.setCatId(5L);
        item.setStatus("show");
        item.setCreateTime(new Date());
        item.setUpdateTime(new Date());
        itemService.save(item);

        File[] files = docFolder.listFiles();
        for (File file : Objects.requireNonNull(files)) {
            if (file.getName().endsWith("png")) {
                upDownloadService.upload2AliByType(item.getId(), file, EFileType.MAIN);
            } else {
                //插入附件
                upDownloadService.upload2AliByType(item.getId(), file, EFileType.ATTACHMENT);
            }
        }
        log.info("--------------- item 插入成功 {} : {}", item.getId(), docFolder.getName());
    }

}
